package org.acmclass.fatworm.test.plaintext;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.acmclass.fatworm.test.FatTestException;

public class FatFileReader {

	private String filename;
	private BufferedReader reader = null;
	private Block current = null;

	public FatFileReader(String filename) throws FatTestException {
		try {
			this.filename = filename;
			reader = new BufferedReader(new FileReader(filename));
		} catch (IOException e) {
			throw new FatTestException("can't open file " + filename, e);
		}
	}

	public boolean next() throws FatTestException {
		current = new Block();
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				if (line.startsWith("#")) {
					continue;
				} else if (line.startsWith("@")) {
					current.addTag(Tag.getTag(line));
				} else if (line.startsWith(";")) {
					return true;
				} else {
					current.addLine(line);
				}
			}
			return false;
		} catch (IOException e) {
			throw new FatTestException("can't read file " + filename, e);
		}
	}

	public Block getBlock() {
		return current;
	}

	public void close() {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
